package net.sf.cldsql.sql2json.main;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;

import net.sf.cldsql.dj.container.DiContainer;
import net.sf.cldsql.dj.container.base.DiAop;
import net.sf.cldsql.dj.container.base.DiSetup;
import net.sf.cldsql.dj.db.ConnPool;
import net.sf.cldsql.dj.mvc.ConnTransAop;
import net.sf.cldsql.dj.mvc.DiService;
import net.sf.cldsql.dj.utl.DiException;
import net.sf.cldsql.dj.utl.Codelet;

/**
 * Builder
 */
public abstract class SjSetup implements DiSetup {
    
    protected DiContainer container;
    protected SjConf conf;
    protected SjController controller;

    public DiContainer build (final String configFilename) {
        // container init
        final DiContainer container = new DiContainer();
        this.container = container;
        
        container.register(SjConf.class, DiContainer.SINGLETON, new Codelet() {public Object run(Object ...args) {
            return new SjConf(configFilename);
            }});
        final SjConf conf = container.<SjConf>get(SjConf.class);
        this.conf = conf;
        
        container.register(ConnPool.class, DiContainer.SINGLETON, new Codelet() {public Object run(Object ...args) {
            String poolName = conf.get(SjConf.SQL_POOLS);
            return new ConnPool(poolName,
                    conf.get(poolName, SjConf.JDBC_DRIVER),
                    conf.get(poolName, SjConf.JDBC_URL),
                    conf.get(poolName, SjConf.JDBC_USERNAME),
                    conf.get(poolName, SjConf.JDBC_PASSWORD),
                    Integer.parseInt(conf.get(poolName, SjConf.MAX_CONN))
                    );
            }});
        
        container.register(SjController.class, SjControllerImpl.class, DiContainer.SINGLETON, new ConnTransAop(container));
        
        final SjController controller = container.get(SjController.class);
        this.controller = controller;
        
        build();

        final String sjServiceName = container.register(SjService.class, SjServiceImpl.class, new ConnTransAop(container));
        controller.register(".*", "^/(GET|POST|PUT|DELETE)/([^/]+)/([^/]+)$", sjServiceName);
        controller.register(".*", "^/(GET|POST|PUT|DELETE)/([^/]+)$", sjServiceName);
        controller.register(".*", "^/([^/]+)/([^/]+)$", sjServiceName);
        controller.register(".*", "^/([^/]+)$", sjServiceName);
        
        return container;
    }
    
    public abstract void build();
    
}
